#!/usr/bin/python
import sys
import os
import pexpect

def expectandshow(child, expect):
        index=child.expect(expect)
        print child.before,child.after,
        return index


path=sys.path[0]

fp_intr = open(path+'/ip','r')

line = fp_intr.readline()
length = len(line)
line=line[0:length-1]
Master_IP=line

cmd="ssh root@"+Master_IP+ " " +\
	"/sbin/chkconfig ypserv off;" + \
	"/sbin/chkconfig ypserv of;" + \
	"/etc/init.d/ypserv stop;" + \
	"/etc/init.d/ypserv start;" + \
	"/usr/lib64/yp/ypinit -m;" + \
	"/sbin/chkconfig ypbind off;" + \
	"/sbin/chkconfig ypbind on;" + \
	"/etc/init.d/ypbind stop;" + \
	"/etc/init.d/ypbind start;"

	
print cmd
password="passw0rd"
scp_child=pexpect.spawn(cmd)
index=expectandshow(scp_child, \
                                ['Are you sure you want to continue connecting', \
                                "root@"+Master_IP+"'s password:", \
				"next host to add:", \
				"Is this correct?  [y/n: y]" , \
                                pexpect.TIMEOUT, \
                                pexpect.EOF])
if index == 0:
        scp_child.sendline('yes')
        ret = expectandshow(scp_child, ["root@"+Master_IP+"'s password:",pexpect.
EOF])
        if ret == 0:
                scp_child.sendline(password)
                ret1 = expectandshow(scp_child, ["next host to add:", pexpect.EOF])
        	if ret1 == 0:
			scp_child.sendcontrol('D')
			ret2 = expectandshow(scp_child, ["Is this correct?  [y/n: y]",pexpect.EOF])
			if ret2 == 0:
				scp_child.sendline("y")
				expectandshow(scp_child, [pexpect.EOF])
			elif ret2 == 1:
				pass
		elif ret1 == 1:
			pass
	elif ret == 1:
                pass
elif index == 1:
        scp_child.sendline(password)
	ret1 = expectandshow(scp_child, ["next host to add:",pexpect.EOF])
        if ret1 == 0:
        	scp_child.sendcontrol('D')
                ret2 = expectandshow(scp_child, ["Is this correct?  [y/n: y]",pexpect.EOF])
                if ret2 == 0:
                     	scp_child.sendline("y")
                        expectandshow(scp_child, [pexpect.EOF])
                elif ret2 == 1:
                        pass
        elif ret1 == 1:
                pass

elif index == 2:
        print "timeout, ignore and continue."
elif index == 3:
        pass

